package com.deep.deepenterpise.common;

import com.deep.deepenterpise.common.redis.GasBlacklistKey;
import com.deep.deepenterpise.common.redis.GasIpKey;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author xyz
 * @version 1.0
 * @title DrRedisCommon
 * @description
 * @create 2024/4/29 13:35
 */
@Component
public class DrRedisCommon {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private static final Integer MAX_COUNT = 3;


    /**
     * @Auth xyz
     * @Desc //TODO 检查是否需要加入黑名单
     * @Time 16:11 2024/4/25
     * @Param [ip]
     */
    public void checkAndJoinBlacklist(String ip) {
        String blacklistKey = GasBlacklistKey.GAS_BLACKLIST_KEY.getKey();
        String ipKey = GasIpKey.GAS_IP_KEY.getKey() + ip;
        // 判断ip监控是否存在，不存在创建
        Long count;
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(ipKey))) {
            // 如果key存在，递增key的值，并返回递增后的值
            count = stringRedisTemplate.opsForValue().increment(ipKey, 1);
        } else {
            stringRedisTemplate.opsForValue().set(ipKey, "1", GasIpKey.GAS_IP_KEY.expireSeconds(),
                    TimeUnit.SECONDS);
            count = 1L;
        }
        if (count != null && count >= MAX_COUNT) {
            // 如果当前次数大于等于最大次数，将ip加入黑名单并返回1
            stringRedisTemplate.opsForSet().add(blacklistKey, ip);
        }
    }


    /**
     * @return boolean
     * @Auth xyz
     * @Desc //TODO 判断是否是黑名单
     * @Time 16:10 2024/4/25
     * @Param [ip]
     */
    public boolean isBlacklist(String ip) {
        Boolean result = stringRedisTemplate.opsForSet().isMember(GasBlacklistKey.GAS_BLACKLIST_KEY.getKey(), ip);
        return Boolean.TRUE.equals(result);
    }
}
